package com.geek.novel.activity.auth

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.activity.auth.view.listener.PwdViewerClickListener
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.listener.ApiResultListener
import com.geek.novel.services.manager.AuthManager
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.SPUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.vo.ApiResult
import kotlinx.android.synthetic.main.activity_login.*

/**
 * 登录页面
 */
class LoginActivity: TitleBarActivity(), ApiResultListener {

	//用户信息管理器
	private lateinit var authManager: AuthManager

	override fun pageName(): String{
		return AppContext.getContext().getString(R.string.title_bar_page_login)
	}
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_login)

		//初始化用户信息管理器
		authManager = AuthManager()
		authManager.setOnApiResultListener(this)
	}

	/**附加组件事件*/
	override fun attachViewChild() {
		//填充账号密码
		val username = SPUtil[Constant.SP_USERINFO_ACCOUNT, SPUtil.usrInfo] as String
		val password = SPUtil[Constant.SP_USERINFO_PASSWORD, SPUtil.usrInfo] as String
		et_login_account.setText(username)
		et_login_password.setText(password)
		//是否勾选记住密码
		val memoryPwdCheck = SPUtil[Constant.SP_USERINFO_MEMORY_PWD, true, SPUtil.usrInfo] as Boolean
		cb_login_memory_pwd.isChecked = memoryPwdCheck

		//账号为空，获取焦点
		if(TextUtils.isEmpty(et_login_account.text)){
			et_login_account.requestFocus()
		}

		//绑定点击事件
		btn_login.setOnClickListener(this)
		btn_forget_psw.setOnClickListener(this)
		btn_goto_regist.setOnClickListener(this)
		//输入框修改事件
		et_login_account.setOnKeyListener(OnEditTextKeyListener())
		et_login_password.setOnKeyListener(OnEditTextKeyListener())
		//显示隐藏密码
		iv_login_password_visible.setOnClickListener(PwdViewerClickListener(et_login_password))
	}

	/**
	 * 绑定点击事件的回调
	 */
	override fun clickEvent(id: Int, v: View) {
		when(id){
			R.id.btn_login->this.login()
			R.id.btn_goto_regist->{
				//前往注册页面
				startActivityForResultByAnim(this, RegistActivity::class.java, Constant.ACTIVITY_RESULT_REGIST)
			}
			R.id.btn_forget_psw->{
				//前往忘记密码页面
				startActivityForResultByAnim(this, ForgetPasswordActivity::class.java, Constant.ACTIVITY_RESULT_FORGET_PASSWORD)
			}
		}
	}


	/**页面回显的事件回调*/
	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)
		if(RESULT_OK == resultCode){
			when(requestCode){
				//从注册页面返回回来，直接关闭登录页面
				Constant.ACTIVITY_RESULT_REGIST->{
					finish()
				}
			}
		}
	}


	/**登录*/
	private fun login(){
		tv_login_error_message.visibility = View.GONE
		val username = et_login_account.text.toString().trim { it <= ' ' }
		val password = et_login_password.text.toString().trim { it <= ' ' }
		LogCatUtil.d("text", "${username}, $password")
		//校验用户名或者密码不为空
		if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
			this.showErrorMessage(et_login_account, R.string.login_error_msg)
			return
		}
		//校验密码
		if (password.length < 6 || password.length > 20) {
			this.showErrorMessage(et_login_password, R.string.hint_register_password)
			return
		}
		//记录用户名、密码
		SPUtil.put(Constant.SP_USERINFO_ACCOUNT, username, SPUtil.usrInfo)
		val checked = cb_login_memory_pwd.isChecked
		SPUtil.put(Constant.SP_USERINFO_MEMORY_PWD, checked, SPUtil.usrInfo)
		if(checked){
			SPUtil.put(Constant.SP_USERINFO_PASSWORD, password, SPUtil.usrInfo)
		}else{
			SPUtil.remove(Constant.SP_USERINFO_PASSWORD, SPUtil.usrInfo)
		}
		//登录
		authManager.login(username, password)
	}


	/**输入值的时候，隐藏错误提示信息*/
	private inner class OnEditTextKeyListener : View.OnKeyListener {
		override fun onKey(arg0: View, arg1: Int, arg2: KeyEvent): Boolean {
			tv_login_error_message.visibility = View.GONE
			return false
		}
	}


	private fun showErrorMessage(view: EditText, stringResId: Int){
		tv_login_error_message.text = resources.getString(stringResId)
		tv_login_error_message.visibility = View.VISIBLE
		view.requestFocus()
		view.selectAll()
	}


	/**处理http请求响应结果*/
	override fun handleResult(result: ApiResult, code: Int) {
		when(code){
			Constant.HTTP_KEY_GET_USERINFO->{
				ToastUtils.toast("登录成功！")
				setResult(RESULT_OK, intent)
				finish()
			}
		}
	}

	override fun handleLogout(code: Int) {
		when(code){
			//获取用户信息
			Constant.HTTP_KEY_GET_USERINFO->{
				ToastUtils.toast("获取用户信息失败！Code: 401")
			}
		}
	}

}